import React,{Fragment} from 'react';
import {StaticRouter,Route} from 'react-router-dom';
import Header from '../components/Header';
import routes from '../routes';
import {renderToString} from 'react-dom/server';
import {matchRoutes,renderRoutes} from 'react-router-config';
import {getServerStore} from '../store';
import {Provider} from 'react-redux';

export default function (req,res) {
	let store=getServerStore(req);
	/**
	let matchedRoutes=routes.filter(route => {
		return matchPath(req.path,route);
	});
	 */
	let matchedRoutes = matchRoutes(routes,req.path);
	let promises=[];
	matchedRoutes.forEach(item => {
		if (item.route.loadData) {
			let promise=new Promise(function (resolve,reject) {
				return item.route.loadData(store).then(resolve,resolve);
			});
			promises.push(promise);
		}	
	});
	Promise.all(promises).then(result => {
		let context={csses:[]};
		const content=renderToString(
			<Provider store={store}>
				<StaticRouter context={context} location={req.path}>
				 {renderRoutes(routes)}
				</StaticRouter>
			</Provider>
		);
		let cssStr='';
		if (context.csses.length>0) {
			cssStr=context.csses.join('\r\n');
		}
		if (context.action == 'REPLACE') {
			return res.redirect(301,context.url);
		} else if (context.notFound) {
			res.status(404);
		}
		res.send(
			`
			<html>
				<head></head>
				<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
				<style>${cssStr}</style>
				<body>
					<div id="root">${content}</div>
					<script>
						window.context = {
							state:${JSON.stringify(store.getState())}
						}
					</script>
					<script src="/client.js"></script>
				</body>
			</html>
			`
		);
	});
	
}